{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# all_different_except_zero_sample_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/sat/all_different_except_zero_sample_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/sat/samples/all_different_except_zero_sample_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Implements AllDifferentExcept0 using atomic constraints.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "def all_different_except_0():\n",
    "    \"\"\"Encode the AllDifferentExcept0 constraint.\"\"\"\n",
    "\n",
    "    # Model.\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # Declare our primary variable.\n",
    "    x = [model.new_int_var(0, 10, f\"x{i}\") for i in range(5)]\n",
    "\n",
    "    # Expand the AllDifferentExcept0 constraint.\n",
    "    variables_per_value = collections.defaultdict(list)\n",
    "    all_values = set()\n",
    "\n",
    "    for var in x:\n",
    "        all_encoding_literals = []\n",
    "        # Domains of variables are represented by flat intervals.\n",
    "        for i in range(0, len(var.proto.domain), 2):\n",
    "            start = var.proto.domain[i]\n",
    "            end = var.proto.domain[i + 1]\n",
    "            for value in range(start, end + 1):  # Intervals are inclusive.\n",
    "                # Create the literal attached to var == value.\n",
    "                bool_var = model.new_bool_var(f\"{var} == {value}\")\n",
    "                model.add(var == value).only_enforce_if(bool_var)\n",
    "\n",
    "                # Collect all encoding literals for a given variable.\n",
    "                all_encoding_literals.append(bool_var)\n",
    "\n",
    "                # Collect all encoding literals for a given value.\n",
    "                variables_per_value[value].append(bool_var)\n",
    "\n",
    "                # Collect all different values.\n",
    "                all_values.add(value)\n",
    "\n",
    "        # One variable must have exactly one value.\n",
    "        model.add_exactly_one(all_encoding_literals)\n",
    "\n",
    "    # Add the all_different constraints.\n",
    "    for value, literals in variables_per_value.items():\n",
    "        if value == 0:\n",
    "            continue\n",
    "        model.add_at_most_one(literals)\n",
    "\n",
    "    model.add(x[0] == 0)\n",
    "    model.add(x[1] == 0)\n",
    "\n",
    "    model.maximize(sum(x))\n",
    "\n",
    "    # Create a solver and solve.\n",
    "    solver = cp_model.CpSolver()\n",
    "    status = solver.solve(model)\n",
    "\n",
    "    # Checks and prints the output.\n",
    "    if status == cp_model.OPTIMAL:\n",
    "        print(f\"Optimal solution: {solver.objective_value}, expected: 27.0\")\n",
    "    elif status == cp_model.FEASIBLE:\n",
    "        print(f\"Feasible solution: {solver.objective_value}, optimal 27.0\")\n",
    "    elif status == cp_model.INFEASIBLE:\n",
    "        print(\"The model is infeasible\")\n",
    "    else:\n",
    "        print(\"Something went wrong. Please check the status and the log\")\n",
    "\n",
    "\n",
    "all_different_except_0()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
